class TreeNode1 {
    val: number
    left: TreeNode1 | null
    right: TreeNode1 | null

    constructor(val?: number, left?: TreeNode1 | null, right?: TreeNode1 | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

function serialize(root: TreeNode1 | null): string {
    let res: string = '['
    let queue: TreeNode1[] = []
    if (root === null) return ''
    queue.push(root)
    while (queue.length) {
        let curr = queue.pop()!
        if (curr === null) res += 'null'
        else {
            res += curr.val + ','
            if (curr.left) queue.push(curr.left)
            if (curr.right) queue.push(curr.right)
        }
    }
    res.substring(0, res.length - 1);
    res += ']'
    return res

};

function deserialize(data: string): TreeNode1 | null {
    let str = data.substring(1, data.length - 1);
    let arr = str.split(',')
    let root = new TreeNode1(Number(arr[0]))
    let queue: TreeNode1[] = []
    let parent: TreeNode1 = root // 当前节点的父节点
    let isLeft = true; // 是不是左边节点
    for (let i = 1; i < arr.length; i++) {
        let curr = getNode(arr[i])
        if (isLeft) parent.left = curr
        else parent.right = curr

        if (curr != null){
            queue.push(curr)
        }
        isLeft = !isLeft
        if (isLeft) queue.pop()

    }
    return root
};

function getNode(val: string): TreeNode1 | null {
    if (val === 'null') {
        return null
    } else {
        return new TreeNode1(Number(val))
    }
}
